<template>
  <view class="container">
    <cu-custom :bgColor="'bg-' + theme.backgroundColor" :isBack="false">
      <!-- <block slot="backText">返回</block> -->
      <block slot="content"> {{ isAppId ? "更新用户" : "支付" }}</block>
    </cu-custom>
    <!-- 支付数据编辑展示 -->
    <view v-if="isDebug" class="form-container">
      <view class="form-item">
        <text class="label">订单号:</text>
        <input class="input" v-model="order_sn" placeholder="请输入订单号" />
      </view>

      <view class="form-item">
        <text class="label">支付类型:</text>
        <input class="input" v-model="payment" placeholder="请输入支付类型" />
      </view>

      <view class="form-item">
        <text class="label">企业编码:</text>
        <input
          class="input"
          v-model="businessnumber"
          placeholder="请输入企业编码"
        />
      </view>

      <view class="form-item">
        <text class="label">Token:</text>
        <input class="input" v-model="token" placeholder="请输入Token" />
      </view>

      <button class="pay-button" @click="payOrder">立即支付</button>
    </view>
    <!-- appId授权数据编辑展示 -->
    <view v-if="isAppIdDebug" class="form-container">
      <view class="form-item">
        <text class="label">token:</text>
        {{ token }}
      </view>

      <view class="form-item">
        <text class="label">openId:</text>
        {{ userInfo.openId }}
      </view>
      <view class="form-item">
        <text class="label">nickName:</text>
        {{ userInfo.nickName }}
      </view>
      <view class="form-item">
        <text class="label">avatarUrl:</text>
        {{ userInfo.headimgUrl }}
      </view>

      <button class="pay-button" @click="updateInfo">立即更新</button>
    </view>

    <view v-if="loding" style="text-align: center; line-height: 300rpx">
      <text>加载中...</text>
    </view>
    <!-- 手动关闭 -->
    <view v-if="paymentSuccess" class="success-container">
      <view class="success-icon">✓</view>
      <view v-if="isAppId" class="success-text">绑定用户成功!</view>
      <view v-else class="success-text">支付成功</view>
      <button class="exit-button" @click="exitMiniProgram">关闭页面</button>
    </view>
  </view>
</template>

<script>
const app = getApp();
import appApi from "utils/AppApi";
export default {
  data() {
    return {
      theme: app.globalData.theme,
      order_sn: null,
      //  企业编码
      businessnumber: null,
      token: null,
      // 支付类型
      payment: "allinpay",
      loding: false,
      // 调试
      isDebug: false,
      paymentSuccess: false,
      // 获取用户信息
      isAppId: false,
      // 显示用户信息 调试
      isAppIdDebug: false,
      userInfo: {},
    };
  },

  onLoad(options) {
    this.userInfo = uni.getStorageSync("user_info") || {};
    // 兼容 本地支付和拉起支付优先本地支付 options 是空对象 本地缓存存在走本地缓存
    let strAppToken = uni.getStorageSync("appToken");
    if (Object.keys(options).length === 0 && strAppToken) {
      options = JSON.parse(strAppToken);
    }
    console.log("options", options);

    if (options.token) {
      // 支付字段
      this.isDebug = options.isDebug || false;
      this.order_sn = options.order_sn || "";
      this.businessnumber = options.businessnumber || "";
      this.token = options.token ? this.base64Decode(options.token) : null;
      // 授权字段
      this.isAppId = options.isAppId || false;
      this.isAppIdDebug = options.isAppIdDebug || false;
      if (this.isAppId) {
        // 更新用户详情
        this.updateInfo();
      } else {
        this.payOrder();
      }
    } else {
      uni.showToast({
        title: "缺少参数",
        icon: "none",
      });
    }
  },

  methods: {
    // 拉起微信支付
    async payOrder() {
      if (!this.order_sn) return;
      this.loding = true;
      try {
        const headers = {
          businessnumber: this.businessnumber || "",
          Authorization: `Bearer ${this.token}`,
          accept: "application/json",
        };
        // 请求后端获取支付参数
        const res = await appApi.wechatPayParams(
          {
            order_sn: this.order_sn,
            wechat_openid: uni.getStorageSync("user_info").openId,
            payment: this.payment || "allinpay",
          },
          headers
        );
        const payRes = res.data.pay_data;
        this.loding = false;
        if (payRes && Object.prototype.hasOwnProperty.call(payRes, 'retcode') && payRes.retcode) {
          uni.showToast({
            title: payRes.retmsg || "订单不是可支付状态",
            icon: "none",
          });
          return;
        }
        
        // 调用微信支付
        uni.requestPayment({
          appId: payRes.appId,
          provider: "wxpay",
          timeStamp: payRes.timeStamp,
          nonceStr: payRes.nonceStr,
          package: payRes.package,
          signType: payRes.signType,
          paySign: payRes.paySign,
          success: (res) => {
            // 支付成功后显示提示界面，等待用户点击退出
            this.showPaymentSuccess();
          },
          fail: (err) => {
            this.loding = false;
            console.error("支付失败", err);
            uni.showToast({
              title: "支付取消或失败",
              icon: "none",
            });
          },
        });
      } catch (error) {
        this.loding = false;
        let msg = error.message || "获取支付参数失败";
        uni.showToast({
          title: msg,
          icon: "none",
        });
      }
    },

    // 更新用户详情
    async updateInfo() {
      if (!this.token) return;
      this.loding = true;
      try {
        const headers = {
          Authorization: `${this.token}`,
          accept: "application/json",
        };
        // 请求后端更新用户详情
        const res = await appApi.customerInfo(
          {
            wechat_openid: this.userInfo.openId,
            wechat_nickname: this.userInfo.nickName || "",
            avatar_url: this.userInfo.headimgUrl || "",
            //"wechat_name": "aaaa",
            // wechat_unionid":Maaaa",
          },
          headers
        );
        this.loding = false;
        if (res.code == 200001) {
          // 成功后显示提示界面，等待用户点击退出
          this.showPaymentSuccess();
        }
      } catch (error) {
        this.loding = false;
        let msg = error.message || "更新用户详情失败";
        uni.showToast({
          title: msg,
          icon: "none",
        });
      }
    },

    // 支付成功后显示提示界面
    showPaymentSuccess() {
      this.paymentSuccess = true;
      this.loding = false;
      // 删除标识
      uni.removeStorageSync("appToken");
      let text = this.isAppId ? "更新成功" : "支付成功";
      uni.showToast({
        title: text,
        icon: "success",
      });
    },

    // 用户点击退出小程序
    exitMiniProgram() {
      // uni.switchTab({
      //   url: '/pages/home/index',
      // });
      // return
      if (uni.exitMiniProgram) {
        uni.exitMiniProgram({
          success: function () {
            console.log("成功退出小程序");
          },
          fail: function (err) {
            console.log("退出小程序失败", err);
            uni.showToast({
              title: "请手动返回",
              icon: "none",
            });
          },
        });
      } else {
        uni.showToast({
          title: "当前环境不支持退出小程序",
          icon: "none",
        });
      }
    },

    // base64 解码token方法
    base64Decode(str) {
      try {
        // 使用 uni.base64ToArrayBuffer 进行解码（如果可用）
        if (uni.base64ToArrayBuffer) {
          // 先转换为 ArrayBuffer，再转换为字符串
          const arrayBuffer = uni.base64ToArrayBuffer(str);
          return String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
        } else {
          // 使用 JavaScript 原生方法进行 base64 解码
          return decodeURIComponent(
            atob(str)
              .split("")
              .map(function (c) {
                return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
              })
              .join("")
          );
        }
      } catch (error) {
        console.error("Base64 解码失败:", error);
        // 如果解码失败，返回原始值
        return str;
      }
    },

    // 判断签名
    handDetermineSignature() {
      let _is = false;
      console.log(
        "当前小程序appId:",
        uni.getAccountInfoSync().miniProgram.appId
      );
      // 优先使用支付参数中返回的appId，如果没有则使用当前小程序的appId
      const paymentAppId =
        payRes.appId || uni.getAccountInfoSync().miniProgram.appId;
      // console.log("使用支付的appId:", paymentAppId);
      // 检查appId是否正确配置
      if (!paymentAppId) {
        uni.showToast({
          title: "支付配置错误，请联系客服",
          icon: "none",
          duration: 3000,
        });
        return _is;
      }
      if (payRes.retcode) {
        uni.showToast({
          title: payRes.retmsg || "订单不是可支付状态",
          icon: "none",
        });
        return _is;
      }
      // 如果支付参数中有appId，使用它
      // if (payRes.appId) {
      //   // 如果支付参数中有appId，使用它
      //   payRes.appId = paymentAppId;
      // } else {
      //   // 否则使用当前小程序的appId
      //   payRes.appId = uni.getAccountInfoSync().miniProgram.appId;
      // }
      return !_is;
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  // padding: 20rpx;
  .order-info {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }
  .pay-button {
    margin-top: 40rpx;
    background-color: #07c160;
    color: white;
    border: none;
    padding: 20rpx;
    border-radius: 10rpx;
  }
}

.success-container {
  text-align: center;
  padding: 100rpx 40rpx;

  .success-icon {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background-color: #07c160;
    color: white;
    font-size: 60rpx;
    line-height: 120rpx;
    margin: 0 auto 40rpx;
  }

  .success-text {
    font-size: 36rpx;
    color: #333;
    margin-bottom: 60rpx;
  }

  .exit-button {
    background-color: #07c160;
    color: white;
    border: none;
    padding: 20rpx 40rpx;
    border-radius: 10rpx;
    font-size: 32rpx;
  }
}

.form-container {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 60rpx 30rpx;
  margin-bottom: 30rpx;

  .form-item {
    margin-bottom: 25rpx;
    display: flex;
    flex-direction: column;
  }

  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
  }

  .input {
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    padding: 30rpx 20rpx;
    font-size: 28rpx;
    height: 100rpx;
    line-height: 70rpx;
    box-sizing: border-box;
  }
}
</style>
